package com.trace.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.trace.app.entity.LoginUser;
import com.trace.app.entity.ResponseResult;
import com.trace.app.entity.Role;
import com.trace.app.entity.User;
import com.trace.app.entity.vo.UserInfoVo;
import com.trace.app.service.LoginService;
import com.trace.app.service.RoleService;
import com.trace.app.service.UserService;
import com.trace.app.util.BeanCopyUtils;
import com.trace.app.util.JWT.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCacheService redisCache;
    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登录成功!", map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userid);
        return new ResponseResult(200, "退出成功");
    }

    @Override
    public ResponseResult register(User user) {
        String finalPasswd = passwordEncoder.encode(user.getPassword());
        User newUser = new User(user.getUsername(), finalPasswd);
        newUser.setEmail(user.getEmail());
        newUser.setPhoneNumber(user.getPhoneNumber());
        userService.insertOne(newUser);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserInfo(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User user = userService.getOne(queryWrapper.eq(User::getUsername, username));
        UserInfoVo userInfo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        Role role = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getId, user.getUserType()));
        userInfo.setType(role.getRemark());

        return ResponseResult.okResult(userInfo);
    }
}